package valid

import (
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	en_translations "github.com/go-playground/validator/v10/translations/en" // 提示语翻译包
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
)

var (
	Trans ut.Translator
)

// Init / 扩展自定义校验器
func Init() *validator.Validate {
	v, ok := binding.Validator.Engine().(*validator.Validate)
	if ok {
		// 修改默认行为，例如停止在第一个错误时返回
		v.SetTagName("validate") // 默认是 "binding"
		//v.RegisterTagNameFunc(func(fld reflect.StructField) string {
		//	// 自定义字段名显示
		//	return fld.Tag.Get("json")
		//})
	} else {
		return nil
	}

	Trans = initValidate("zh", v)

	addConstomValid(v, Trans)

	return v
}

func initValidate(local string, validate *validator.Validate) ut.Translator {
	// en 英文，zh 中文
	en := en.New()
	zh := zh.New()
	//初始化翻译器，并指定支持的语种
	uni := ut.New(zh, en, zh)
	// 获取指定语种的翻译器
	trans, _ := uni.GetTranslator(local)

	switch local {
	case "en":
		en_translations.RegisterDefaultTranslations(validate, trans)
	case "zh":
		zh_translations.RegisterDefaultTranslations(validate, trans)
	default:
		zh_translations.RegisterDefaultTranslations(validate, trans)
	}

	return trans
}

func addConstomValid(v *validator.Validate, trans ut.Translator) {

	addEmail0Valid(v, trans)

}
